import {Component} from "react";

export class MyComponent extends Component{
    constructor(){
        super();
        console.log('MyComponent constructor');
        this.changeData = this.changeData.bind(this);
    }
    componentDidUpdate(){
        console.log('MyComponent componentDidUpdate');
    }
    componentWillUpdate(){
        console.log('MyComponent componentWillUpdate');
    }
    componentDidMount(){
        console.log('MyComponent componentDidMount');
    }
    componentWillMount(){
        console.log('MyComponent componentWillMount');
        // let data = localStorage.getItem("data");
        // this.setState({data});
    }
    componentWillReceiveProps(){
        console.log('MyComponent componentWillReceiveProps');
    }
    shouldComponentUpdate(){
        console.log('MyComponent shouldComponentUpdate');
    }
    changeData(e){
        this.setState({data: 'You are my good friend.'});
    }
    //@todo 不需要声明到 state 里面也可以？可以动态添加 state 字段？
    render(){
        console.log("MyComponent render");
        return (<div><div>HOC:{this.props.data}</div><div><button onClick={this.changeData}>更改data值</button></div></div>)
    }
}

export default function withPersistentData(WrappedComponent){
    //这是匿名类？
    return class extends Component{

        componentWillMount(){
            console.log("withPersistentData componentWillMount");
            // let data = localStorage.getItem("data");
            //@todo 这里为什么不能传递对象作为属性值?
            var data = 'hello world'; 
            // {tip: '没有数据，我是默认的'}
            this.setState({data});
        }
        render(){
            console.log("withPersistentData render");
            return <WrappedComponent data={this.state.data} {...this.props}></WrappedComponent>
        }
    }
}

